package com.example.chatbackend.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping("/media")
public class MediaController {
    @Value("${media.baseDir:}")
    private String mediaBaseDir;

    @GetMapping("/{file:.+}")
    public ResponseEntity<FileSystemResource> getMedia(@PathVariable("file") String file) {
        String baseDir = (mediaBaseDir != null && !mediaBaseDir.isEmpty())
                ? mediaBaseDir
                : System.getProperty("java.io.tmpdir") + File.separator + "chat-media";
        File f = new File(baseDir, file);
        if (!f.exists() || !f.isFile()) {
            return ResponseEntity.notFound().build();
        }
        MediaType mt = file.endsWith(".wav") ? MediaType.valueOf("audio/wav") : MediaType.APPLICATION_OCTET_STREAM;
        return ResponseEntity.ok()
                .contentType(mt)
                .body(new FileSystemResource(f));
    }
}


